package cn.fancy.sdk.floatwindow;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import java.io.File;
import java.util.List;

import cn.fancy.sdk.FancyManager;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.entity.GuildBaseInfo;
import cn.fancy.sdk.login.utils.AccountHelper;
import cn.fancy.sdk.login.utils.AccountHelper.Local_Account;
import cn.fancy.sdk.login.utils.DBHelper;

@SuppressLint("SetJavaScriptEnabled")
public class FloatWebView extends Dialog implements android.view.View.OnClickListener {
    private static final String TAG = FloatWebView.class.getName();
    private boolean firenter = true;

    private static ValueCallback<Uri[]> mUploadMessage;

    public FloatWebView instance;
    private final String url;

    private ClipboardManager clisign;
    private DBHelper dbHelper;
    static int redpointModule = 0;
    private Context mContext;
    private WebView webveiw_page;
    private boolean isShowing;
    private ImageView webview_load;
    private ProgressBar progressBar;

    public boolean isShowing() {
        return isShowing;
    }

    public FloatWebView(Context context, String urlString) {
        super(context);
        isShowing = true;

        instance = this;
        mContext = getContext();
    
        url = urlString;

        dbHelper = DBHelper.getInstance(mContext);
        clisign = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
    
        Window mWindow = getWindow();
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mWindow.setGravity(Gravity.START | Gravity.TOP);
        mWindow.setType(LayoutParams.TYPE_APPLICATION);

        mWindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN); // full screen
        mWindow.setBackgroundDrawable(new ColorDrawable(
                android.graphics.Color.TRANSPARENT)); // transparent-background
        mWindow.getDecorView().setPadding(0, 0, 0, 0);
        mWindow.setDimAmount(0.0f); // make previous-activity not dark
    
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        WindowManager sysWindowManager = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        mWindow.getWindowManager();
        // 这里必须用 system的，不然dialog被分配高度 在部分机型中 会因为底部状态栏 而 减少
        // 导致底部有一个透明区域，
        sysWindowManager.getDefaultDisplay().getMetrics(mDisplayMetrics);
        int mDialogWidth = mDisplayMetrics.widthPixels * 4 / 5;
        int mDialogHeight = mDisplayMetrics.heightPixels * 6 / 7;

        this.setContentView(ResUtil.getLayoutId(mContext,
                "guild_float_webview"));

        mWindow.setWindowAnimations(ResUtil.getStyleId(mContext,
                "fancy_float_webview_anim"));
        RelativeLayout webview_layout = (RelativeLayout) this.findViewById(ResUtil.getId(
            mContext, "guild_float_webview_layout"));
        webview_load = (ImageView) this.findViewById(ResUtil.getId(mContext, "guild_float_webview_load"));
        progressBar = (ProgressBar) this.findViewById(ResUtil.getId(mContext, "fancy_progress_loading"));
        
        webveiw_page = (WebView) this.findViewById(ResUtil.getId(mContext,
                "guild_float_webview_page"));
        RelativeLayout closeout_layout = (RelativeLayout) this.findViewById(ResUtil.getId(
            mContext, "guild_float_closeout"));
        closeout_layout.setOnClickListener(this);

        // set dialog size
        RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) webview_layout
                .getLayoutParams();
        linearParams.height = mDialogHeight;
        linearParams.width = mDialogWidth;
        linearParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        webview_layout.setLayoutParams(linearParams);
    }

    private void loadWebView() {
        Log.e("pageinitview", "pageinitview");
        WebSettings webSettings = webveiw_page.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAppCacheEnabled(false);
        webSettings.setDatabaseEnabled(false);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webveiw_page.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webveiw_page.setDownloadListener(new QCDownloadListener());

        // 不要设置JS缓存
        String loadingUrl = url;
        // 加载页面，假如要点击小红点自动跳到活动更新页，应修改url
        webveiw_page.loadUrl(loadingUrl);

        webveiw_page.addJavascriptInterface(new JSInterface(), "JSInterface");
        webveiw_page.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("itunes.apple.com")) {
                    view.stopLoading();
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (url.contains("itunes.apple.com")) {
                    return;
                }

                super.onPageStarted(view, url, favicon);
                if (firenter) {
                    firenter = false;
                    new Thread() {
                        public void run() {
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                webveiw_page
                        .loadUrl("javascript:function closeFloat(){JSInterface.closeFloat();}");
                webveiw_page
                        .loadUrl("javascript:function loginOut(){JSInterface.loginOut();}");
                webveiw_page
                        .loadUrl("javascript:function contactQQ(qqnumber){JSInterface.openmqq(qqnumber);}");
                webveiw_page
                        .loadUrl("javascript:function contactMobile(number){JSInterface.contactmobile(number);}");
                webveiw_page
                        .loadUrl("javascript:function hideFloat(){JSInterface.hideFloat();}");
                webveiw_page
                        .loadUrl("javascript:function DownLoadFileToC(downurl,filetype){JSInterface.downloadfile(downurl,filetype);}");
                webveiw_page
                        .loadUrl("javascript:function resetUserPassword(user){JSInterface.resetpassword(userjson);}");
                webveiw_page
                        .loadUrl("javascript:function FloatBindMobile(username){JSInterface.BindMobile(username);}");
                // 跳转到手机浏览器
                webveiw_page
                        .loadUrl("javascript:function openBrowserWithUrl(url){JSInterface.openBrowser(url);}");
                // 复制文本
                webveiw_page
                        .loadUrl("javascript:function copyInfo(number){JSInterface.copyPackageNumber(number);}");
                // 打开自定义浏览器，活动详情用
                webveiw_page
                        .loadUrl("javascript:function openCustomBrowserWithUrl(url){JSInterface.openCustomBrowser(url);}");
                // 在web上实现下载的接口
                //webveiw_page
                //        .loadUrl("javascript:function webDownloadWithUrl(url,state,id,packname,version){JSInterface.webDownload(url,state,id,packname,version);}");
                // 新增接口打开微信
                webveiw_page.loadUrl("javascript:function openWechatFunc(){JSInterface.openWechat();}");
                // 新增加载完毕函数
                webveiw_page.loadUrl("javascript:paraminitSet()");
                
                //去除loading
                webview_load.setVisibility(View.GONE);
                progressBar.setVisibility(View.GONE);
            }
        });

        webveiw_page.setWebChromeClient(new WebChromeClient() {
            // Android 5.0+
            @Override
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePath,
                                             FileChooserParams fileChooserParams) {
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                }
                mUploadMessage = filePath;
                Intent intent = new Intent(mContext,
                        FloatWindowActivityDetail.class);
                mContext.startActivity(intent);
                return true;
            }
        });
    }

    private class QCDownloadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype, long contentLength) {
            // 参数1 下载链接 参数2 文件存放名字 参数3 下载提示
            // 创建下载任务,downloadUrl就是下载链接
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));
            // 设置允许下载的网络环境
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
                    | DownloadManager.Request.NETWORK_MOBILE);
            // 在Notification显示下载进度
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE
                    | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            String filename = url.substring(url.lastIndexOf("/") + 1);
            // 指定下载路径和下载文件名
            request.setDestinationInExternalPublicDir("/download/", filename);
            request.setDestinationInExternalPublicDir("dirType", "guild.apk");
            // 显示下载界面
            request.setVisibleInDownloadsUi(true);
            request.setTitle("游戏下载中");
            DownloadManager downloadManager = (DownloadManager) mContext
                    .getSystemService(Context.DOWNLOAD_SERVICE);
            // 将下载任务加入下载队列，否则不会进行下载
            long fileid = downloadManager.enqueue(request);
            if (url.endsWith(".apk")) {
                DownUpdateBroadcastReceiver.addDownloadId(fileid);
            }
        }
    }

    public class JSInterface {
        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void closeFloat() {
            // 再次弹起浮标
            showFloat();
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void loginOut() {
            changeU();
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void openmqq(String qqnumber) {
            boolean canOpenQQ = false;
            final PackageManager packageManager = mContext.getPackageManager();
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
            if (pinfo != null) {
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
                    if (pn.equals("com.tencent.mobileqq")) {
                        canOpenQQ = true;
                        break;
                    }
                }
            }

            if (canOpenQQ) {
                String qqurl = "http://wpa.b.qq.com/cgi/wpa.php?ln=2&uin="
                        + qqnumber;
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(qqurl));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            } else {
                String qqurl = "http://crm2.qq.com/page/portalpage/wpa.php?aty=1&a=0&curl=&ty=1&uin="
                        + qqnumber;
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(qqurl));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void contactmobile(String number) {
            Intent mobileintent = new Intent(Intent.ACTION_CALL,
                    Uri.parse("tel:" + number));
            mobileintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(mobileintent);
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void downloadfile(String downurl, String filetype) {
            // 参数1 下载链接 参数2 文件存放名字 参数3 下载提示
            // 创建下载任务,downloadUrl就是下载链接
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(downurl));
            // 设置允许下载的网络环境
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
                    | DownloadManager.Request.NETWORK_MOBILE);
            // 在Notification显示下载进度
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE
                    | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            String filename = downurl.substring(downurl.lastIndexOf("/") + 1);
            // 指定下载路径和下载文件名
            request.setDestinationInExternalPublicDir("/download/", filename);
            // 显示下载界面
            request.setVisibleInDownloadsUi(true);
            DownloadManager downloadManager = (DownloadManager) mContext
                    .getSystemService(Context.DOWNLOAD_SERVICE);
            // 将下载任务加入下载队列，否则不会进行下载
            long fileid = downloadManager.enqueue(request);

            // 假设是apk需要自动安装功能
            if (filetype != null && filetype.equals("apk")) {
                DownUpdateBroadcastReceiver.addDownloadId(fileid);
            }
            Toast.makeText(mContext, "已加入下载，请注意查看", Toast.LENGTH_SHORT).show();
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void hideFloat() {
            // 隐藏浮标
            if (instance != null) {
                instance.dismiss();
                instance = null;
                FancyManager.getInstance().closeTimer();
            }
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void resetpassword(String user,String pass ) {

            // 重设密码
            GuildBaseInfo.getInstance().ResetPassword(pass);
            DBHelper.SDK_ACCOUNT s_acct = new DBHelper.SDK_ACCOUNT();
            s_acct.user_name = user;
            s_acct.user_password = pass;
            dbHelper.updateAccount(s_acct);

            Local_Account local_acct = new Local_Account();
            local_acct.username = user;
            local_acct.password = pass;
            AccountHelper.updateLocalAccounts(local_acct);
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void BindMobile(String username) {
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void openWechat() {
            //打开微信页面
            try {
                // set our wechat to clipboard
                ClipboardManager clipboard = (ClipboardManager)
                        mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                ContentResolver cr = mContext.getContentResolver();
                ClipData clip = ClipData.newPlainText("simple text", "gh_a6f8f6882ef4");
                clipboard.setPrimaryClip(clip);

                Intent intent = new Intent(Intent.ACTION_MAIN);
                ComponentName componentName = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setComponent(componentName);
                mContext.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(mContext, "检查到手机没安装微信，请安装后使用该功能", Toast.LENGTH_LONG).show();
            }
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void copyPackageNumber(String number) {
            ClipData clipData = ClipData.newPlainText("label", number);
            clisign.setPrimaryClip(clipData);
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void openBrowser(String url) {
            Intent brointent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            brointent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(brointent);
        }

        @android.webkit.JavascriptInterface
        // 4.0之后要加这个注解
        public void openCustomBrowser(String url) {
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                Intent brointent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                brointent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(brointent);
            } else {
                Log.e("openbrowser", "openbrowser:" + url);
                Intent intent = new Intent(mContext,
                        FloatWindowActivityDetail.class);
                intent.putExtra("custombrowserurl", url);
                mContext.startActivity(intent);
            }
        }

    }

    // 账号切换
    private void changeU() {
        if (instance != null) {
            instance.dismiss();
            instance = null;
            FancyManager.getInstance().logout(mContext);
            FloatWindowService.isshowflat = false;
        }
    }

    // 重新
    private void showFloat() {
        // 再次弹起浮标
        if (instance != null) {
            instance.dismiss();
            instance = null;
            // MyWindowManager.createfloatWindow(gameContext);
            FloatWindowService.canopenfloat = true;
            FloatWindowService.isshowflat = false;
        }
    }

    @Override
    public void show() {
        super.show();
        loadWebView();
    }

    private boolean isSplashExist(String splashpath) {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return false;
        }
        File splashfile = new File(splashpath);
        return splashfile.exists();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FancyManager.getInstance().closeTimer();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "onStop");
        webveiw_page.destroy();
        showFloat();
        isShowing = false;

        FloatWebView.redpointModule = 0;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == ResUtil.getId(mContext, "guild_float_closeout")) {
            webveiw_page.destroy();
            showFloat();
            isShowing = false;

            FloatWebView.redpointModule = 0;
        }
    }
}
